﻿using MediatR;
using RedDragon.Common.Domain.Supplier;
using RedDragon.Common.Dtos;
using RedDragon.Common.Infrastructure.Interface;
using RedDragon.ERP.ErroCodeEnum;
using SqlSugar;
using T.Common.Domain.Common;

namespace RedDragon.ERP.API.Application.Commands.Supplieries
{
    /// <summary>
    /// 获取供应商信息
    /// </summary>
    public class SearchSupplierHandler : IRequestHandler<SearchSupplierCommand, Result<PageResultDto<SupplierDto>>>
    {
        private readonly ISqlSugarClient _db;

        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<SearchSupplierHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="db"></param>
        /// <param name="logger"></param>
        public SearchSupplierHandler(ISqlSugarClient db, ILogger<SearchSupplierHandler> logger)
        {
            _db = db;
            _logger = logger;
        }

        /// <summary>
        /// 获取供应商信息显示
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result<PageResultDto<SupplierDto>>> Handle(SearchSupplierCommand request, CancellationToken cancellationToken)
        {
            var result = new Result<PageResultDto<SupplierDto>>() { Code = (int)CommonErrorCode.Search };
            //实例化分页
            var page = new PageResultDto<SupplierDto>() { TotalCount = 0, PageCount = 0, List = new List<SupplierDto>() };
            try
            {
                //总条数
                RefAsync<int> totalCount = 0;
                //总页数
                RefAsync<int> totalPage = 0;
                //四表联查
                var query = _db.Queryable<Suppliers, Classifications, Countrys, Citys>((s, t, g, c) => s.ClassificationId == t.ClassIficationsId && s.CountryId == g.CountryId && s.CityId == c.CityId).Where(s => s.IsSupplier == 1)
                    .Select((s, t, g, c) => new SupplierDto()
                    {
                        SupplierId = s.SupplierId,
                        SupplierCoding = s.SupplierCoding,
                        SupplierName = s.SupplierName,
                        SupplierDiff = s.SupplierDiff,
                        SupplierPhone = s.SupplierPhone,
                        SupplierAddress = s.SupplierAddress,
                        CountryId = s.CountryId,
                        CityId = s.CityId,
                        ClassificationId = s.ClassificationId,
                        SupplierLabel = s.SupplierLabel,
                        CompanyLogo = s.CompanyLogo,
                        Identification = s.Identification,
                        SupplierStatus = s.SupplierStatus,
                        IsSupplier = s.IsSupplier,
                        CreatedOwner = s.CreatedOwner,
                        CreatedTime = s.CreatedTime,
                        UpdateOwner = s.UpdateOwner,
                        UpdateTime = s.UpdateTime,
                        ExamineOwner = s.ExamineOwner,
                        ExamineTime = s.ExamineTime,
                        ClassIficationsName = t.ClassIficationsName,
                        CountryName = g.CountryName,
                        CityName = c.CityName,
                    });
                //供应商编码模糊查
                if (!string.IsNullOrEmpty(request.SupplierCoding))
                {
                    query = query.Where(s => s.SupplierCoding.Contains(request.SupplierCoding));
                }
                //供应商名称模糊查
                if (!string.IsNullOrEmpty(request.SupplierName))
                {
                    query = query.Where(s => s.SupplierName.Contains(request.SupplierName));
                }
                //状态精确查
                if (request.SupplierStatus != 0)
                {
                    query = query.Where(s => s.SupplierStatus == request.SupplierStatus);
                }
                //供应商类型精确查
                if (!string.IsNullOrEmpty(request.SupplierDiff))
                {
                    query = query.Where(s => s.SupplierDiff == request.SupplierDiff);
                }
                //所在城市精确查
                if (request.CityId != 0)
                {
                    query = query.Where(s => s.CityId == request.CityId);
                }
                //分页
                var list = await query.ToPageListAsync(request.PageIndex, request.PageSize, totalCount, totalPage);
                //总条数
                page.TotalCount = totalCount;
                //总页数
                page.PageCount = totalPage;
                //显示
                page.List = list;
                if (page.List.Any())
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Data = page;
                    result.Msg = "获取供应商信息显示成功";
                }
            }
            catch (Exception ex)
            {
                result.Msg = "获取供应商信息显示异常" + ex.Message;
                _logger.LogError("获取供应商信息显示异常" + ex.Message);
            }
            return result;
        }
    }
}
